package com.easy.work.function;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.base.syslib.Logs;
import com.base.syslib.util.AndroidUtils;
import com.base.syslib.util.AnimUtils;
import com.base.syslib.util.JsonParse;
import com.base.syslib.util.MessageTools;
import com.base.syslib.util.TextUtil;
import com.easy.work.MainActivity;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseActivity;
import com.easy.work.app.CommonValue;
import com.easy.work.bean.UserInfo;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.UserInfoResponse;
import com.easy.work.http.request.UserInfoRequest;
import com.easy.work.http.request.UserLoginRequest;
import com.easy.work.utils.SP.SPKey;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.apache.http.entity.StringEntity;
import org.apache.http.protocol.HTTP;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by zzgpc on 2017-9-10.
 * 登录
 */
public class LoginActivity extends BaseActivity {
    public static void start(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    public static void start(Context context, String phone, String psw) {
        AppSession.saveAppSessionDataNoId(SPKey.phone, "");
        AppSession.saveAppSessionDataNoId(SPKey.password, "");
        Intent intent = new Intent(context, LoginActivity.class);
        intent.putExtra("phone", phone);
        intent.putExtra("psw", psw);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        context.startActivity(intent);
    }

    @BindView(R.id.img_finish)
    ImageView imgFinish;
    @BindView(R.id.et_username)
    EditText etUsername;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.tv_findpw)
    TextView tvFindpw;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    private String tag = "LoginActivity";
    private boolean ishide = true;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        isShowTop = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        String phone = AppSession.getAppSPDataNoId(SPKey.phone);
        String psd = AppSession.getAppSPDataNoId(SPKey.password);
        String userId = AppSession.getInstance().getUserId();
        if (TextUtil.isNotNull(phone) && TextUtil.isNotNull(psd) && TextUtil.isNotNull(userId)) {
            MainActivity.startActivity(this);
            finish();
            return;
        }
        if (getIntent().hasExtra("phone")) {
            phone = getIntent().getStringExtra("phone");
        }
        if (getIntent().hasExtra("psd")) {
            psd = getIntent().getStringExtra("psd");
        }
        etUsername.setText(phone);
        etPassword.setText(psd);

        imgFinish.setVisibility(View.INVISIBLE);
        String registerText = "没有账号，去注册";
        SpannableStringBuilder spannable = new SpannableStringBuilder(registerText);
        spannable.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.login_start_bg)), 6, 8
                , Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvRegister.setText(spannable);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        String mobil = appSession.getMobile();
//        etusername.setText(mobil);
//        etpassword.setText(PreferencesUtils.getString(oThis, "dlmm", "").toString().trim());
    }


    // 登录
    private void login() {
        showMyDialog(getString(R.string.logining));
        Logs.e(tag, "调用登录  login");
        int ecolor = Color.RED; // whatever color you want
        ForegroundColorSpan fgcspan = new ForegroundColorSpan(ecolor);
        final String phone = etUsername.getText().toString().trim();
        final String psd = etPassword.getText().toString().trim();
        if (TextUtil.isNull(phone)) {
            String estring = "手机号码不能为空！";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etUsername.setError(ssbuilder);
            return;
        }
        if (!TextUtil.isMobile(phone)) {
            String estring = "请输入正确的手机号";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etUsername.setError(ssbuilder);
            return;
        }
        if (TextUtil.isNull(psd)) {
            String estring = "请输入密码";
            SpannableStringBuilder ssbuilder = new SpannableStringBuilder(estring);
            ssbuilder.setSpan(fgcspan, 0, estring.length(), 0);
            etPassword.setError(ssbuilder);
            return;
        }
        final String psdMD5 = TextUtil.stringToMD5(psd);


        {
            // TODO Auto-generated method stub
            // begin to login
            RequestParams params = new RequestParams();

            try {

                UserLoginRequest request = new UserLoginRequest();
                request.setUid(phone);
                request.setRid("mobile");
                request.setPwd(psdMD5);
                request.setforAccessToken(true);
                ObjectMapper mapper = new ObjectMapper();
                String json = mapper.writeValueAsString(request);
                params.setBodyEntity(new StringEntity(json, "UTF-8"));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // send request

            HttpUtils http = new HttpUtils();
            params.addHeader("Content-Type", "application/json");
            params.addHeader("charset", HTTP.UTF_8);
            http.send(HttpRequest.HttpMethod.POST, CommonValue.BASE_HOST_LOGIN, params,

                    new RequestCallBack<String>() {

                        @Override
                        public void onStart() {
                            Logs.d(tag, "conn...  login  start");
                            if (!isFinishing()) {

                            }
                        }

                        @Override
                        public void onLoading(long total, long current, boolean isUploading) {

                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> responseInfo) {
                            Logs.d(tag, "Receive response:" + responseInfo.result);
                            closeDialog();
//                            if (AppSession.tokenId != null) {
                            //如果登录成功了，则做一些初始化工作
                            //如果登录成功了，则做一些初始化工作
                            int code = 0;
                            String result = responseInfo.result;
                            UserInfoResponse resp = null;
                            resp = new Gson().fromJson(result, UserInfoResponse.class);
                            code = resp.getCode();
                            if (result.indexOf("\"body\":") != -1) {
                                // Success
                                resp = JsonParse.getInstance().getObjectFromJson(result, UserInfoResponse.class);
                            }

                            if (code == 200) {
                                AppSession.tokenId = resp.getProperties().accessToken;
                                AppSession.saveAppSessionDataNoId("tokenId", AppSession.tokenId);
                                String userID = resp.getBody().id;
                                AppSession.getInstance().setUserId(userID);
                                AppSession.saveAppSessionDataNoId(SPKey.phone, phone);
                                AppSession.saveAppSessionDataNoId(SPKey.password, psd);
//                                getUserInfo(userID);
                                SplashScreenActivity.start(LoginActivity.this);
//                                MainActivity.startActivity(LoginActivity.this);
                                finish();
                            } else if (code == 404) {
                                MessageTools.showToast(getApplicationContext(), "未找到该用户");
                            } else if (code == 501) {
                                MessageTools.showToast(getApplicationContext(), "用户名或密码错误");
                            } else {
                                MessageTools.showToast(getApplicationContext(), resp.getMessage());
                            }

                        }

                        @Override
                        public void onFailure(HttpException error, String msg) {
                            Logs.e(tag, "onFailure:" + error.getExceptionCode() + " msg :"
                                    + msg);
                            MessageTools.showToast(getApplicationContext(), msg);
                            closeDialog();
                        }
                    });

        }

    }


    @OnClick({R.id.img_finish, R.id.btn_login, R.id.tv_findpw, R.id.tv_register})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.img_finish:
                finish();
                break;
            case R.id.btn_login:
                AndroidUtils.closeKeyboard(getApplicationContext(), etPassword);
                login();
//                MainActivity.startActivity(LoginActivity.this);
                break;
            case R.id.tv_findpw:
                ResetPasswordAct.start(this);
                break;
            case R.id.tv_register:
                intent = new Intent(oThis, RegisterActivity.class);
                startActivity(intent);
                AnimUtils.inRightOutleft(oThis);
                break;
        }
    }

}
